package com.wondertek.mist.utils;

import java.io.ByteArrayOutputStream;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Base64;

public class ImageResources {

	 private static WeakHashMap<Integer, WeakReference<Bitmap>> mBitmaps = new WeakHashMap<Integer, WeakReference<Bitmap>>();
	
	 public static int getImageWidth(Context cxt,Integer imgId) {
		return getCacheBitmap(cxt,imgId).getWidth();
	}

	public static int getImageHeight(Context cxt,Integer imgId) {
		return getCacheBitmap(cxt,imgId).getHeight();
	}	

	public static Bitmap getCacheBitmap(Context cxt,Integer imgId) {
		if (mBitmaps.containsKey(imgId)) {
			WeakReference<Bitmap> softReference = mBitmaps.get(imgId);
			Bitmap bitmap = softReference.get();
			if (bitmap != null && !bitmap.isRecycled()) {
				return bitmap;
			}
		}
		Bitmap sd_img = getBitmap(cxt,imgId);
		if (sd_img != null && !sd_img.isRecycled()) {
			mBitmaps.put(imgId, new WeakReference<Bitmap>(sd_img));
		}
		return sd_img;
	}
	
	private static Bitmap getBitmap(Context cxt,Integer imgId) {
		return BitmapFactory.decodeResource(cxt.getResources(), imgId);
	}
		
	/** 2013/11/18 chengshaohua **/
	public static Bitmap getBase64FromString(String st) {
		if(st==null) return null;
		Bitmap bitmap = null;
		try {
			 byte[] bitmapArray = Base64.decode(st, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, bitmapArray.length,0);
		} catch (Exception ex){
			ex.printStackTrace();
		}
		
		return bitmap;
	}
	
	// 将Bitmap转换成字符串
	public static String bitmaptoString(Bitmap bitmap) {

		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);

		return string;
	}
}
